package com.pdool.game.core.res;

import cn.hutool.core.map.MapUtil;

import java.util.Map;

/**
 * 资源操作类
 *
 * @author 香菜
 */
public class ResOp {
    private Long roleId;
    Map<String, Object> addMap = MapUtil.newHashMap();
    Map<String, Object> costMap = MapUtil.newHashMap();

    public ResOp(Long roleId) {
        this.roleId = roleId;
    }

    public void add(String addStr) {
        String[] s = addStr.split("_");
        String type = s[0];
        Object o = addMap.get(type);
        AbsRes absRes = ResTypeManager.getInstance().allResMap.get(type);
        Object merge = absRes.merge(roleId, s, o);
        addMap.put(type, merge);
    }

    public void cost(String costStr) {
        String[] s = costStr.split("_");
        String type = s[0];
        Object o = costMap.get(type);
        AbsRes absRes = ResTypeManager.getInstance().allResMap.get(type);
        Object merge = absRes.merge(roleId, s, o);
        costMap.put(type, merge);
    }

    public boolean check() {
        for (Map.Entry<String, Object> entry : addMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            AbsRes<Object> absRes = ResTypeManager.getInstance().allResMap.get(key);
            if (!absRes.canAdd(roleId, value)) {
                return false;
            }
        }
        for (Map.Entry<String, Object> entry : costMap.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            AbsRes<Object> absRes = ResTypeManager.getInstance().allResMap.get(k);
            if (!absRes.canDec(roleId, v)) {
                return false;
            }
        }
        return true;
    }

    public boolean op() {
        if (!check()){
            return false;
        }
        for (Map.Entry<String, Object> entry : addMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            AbsRes absRes = ResTypeManager.getInstance().allResMap.get(key);
            absRes.add(roleId, value);
        }

        for (Map.Entry<String, Object> entry : costMap.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            AbsRes absRes = ResTypeManager.getInstance().allResMap.get(k);
            absRes.dec(roleId, v);
        }

        return true;
    }
}
